import os
import argparse
from collections import defaultdict

def analyze_log(log_file, output_file=None, keywords=None):
    """
    分析日志文件
    :param log_file: 日志文件路径
    :param output_file: 分析结果输出文件
    :param keywords: 要搜索的关键词，用逗号分隔，如'ERROR,WARN'
    """
    if not keywords:
        keywords = ['ERROR', 'WARN', 'WARNING', 'CRITICAL']
    else:
        keywords = [k.upper() for k in keywords.split(',')]
    
    # 统计各关键词出现次数
    keyword_counts = defaultdict(int)
    # 存储包含关键词的行
    keyword_lines = defaultdict(list)
    
    try:
        with open(log_file, 'r', encoding='utf-8', errors='ignore') as f:
            line_num = 0
            for line in f:
                line_num += 1
                line_upper = line.upper()
                for keyword in keywords:
                    if keyword in line_upper:
                        keyword_counts[keyword] += 1
                        keyword_lines[keyword].append((line_num, line.strip()))
        
        # 生成分析报告
        report = []
        report.append(f"日志文件分析报告: {log_file}")
        report.append(f"分析时间: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        report.append(f"总记录数: {line_num}")
        report.append("\n关键词统计:")
        for keyword, count in keyword_counts.items():
            report.append(f"  {keyword}: {count} 次")
        
        report.append("\n详细记录:")
        for keyword, lines in keyword_lines.items():
            report.append(f"\n{keyword} 记录:")
            for line_num, content in lines[:10]:  # 只显示前10条
                report.append(f"  行 {line_num}: {content}")
            if len(lines) > 10:
                report.append(f"  ... 还有 {len(lines)-10} 条记录未显示")
        
        # 打印报告
        report_str = '\n'.join(report)
        print(report_str)
        
        # 保存到文件
        if output_file:
            with open(output_file, 'w', encoding='utf-8') as f:
                f.write(report_str)
            print(f"\n报告已保存到: {output_file}")
    
    except Exception as e:
        print(f"分析失败: {str(e)}")

if __name__ == "__main__":
    import datetime  # 延迟导入，仅在主程序运行时需要
    parser = argparse.ArgumentParser(description='日志文件分析脚本')
    parser.add_argument('logfile', help='日志文件路径')
    parser.add_argument('--output', help='分析结果输出文件')
    parser.add_argument('--keywords', help='要搜索的关键词，用逗号分隔')
    
    args = parser.parse_args()
    
    analyze_log(
        log_file=args.logfile,
        output_file=args.output,
        keywords=args.keywords
    )
